'''
1.获取多个设备，根据每个设备不同，获取产生不一样的端口，最后产生的数量和设备数一致。
2.启动多个的appium 的服务
3.启动进程池，端口和app相互绑定。进程和用例绑定
4.启动进程进行测试。
'''

import platform
import subprocess
from multiprocessing import Process, Pool
import time, urllib.request
import threading, os


# 启动服务的线程
class RunServer(threading.Thread):
    def __init__(self, cmd):
        threading.Thread.__init__(self)
        self.cmd = cmd

    def run(self):
        os.system(self.cmd)


def check_staus(url):
    time.sleep(10)
    try:
        response = urllib.request.urlopen(url, timeout=5)
        if str(response.getcode()).startswith("2"):
            return True
    except Exception as e:
        print('appium 端口 启动失败')
        return False

def start(port_list: list):

    for i in range(0, len(port_list)):
        cmd = "appium  -p %s  " % (
            port_list[i])
        if platform.system() == "Windows":  # windows下启动server
            t1 = RunServer(cmd)
            p = Process(target=t1.start())
            p.start()
            while True:
                time.sleep(4)
                if check_staus("http://127.0.0.1:" + port_list[i] + "/wd/hub/status"):
                    break
        else:
            appium = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1,
                                      close_fds=True)
            while True:
                appium_line = appium.stdout.readline().strip().decode()
                time.sleep(2)
                if 'listener started' in appium_line or 'Error: listen' in appium_line:
                    print("----server启动成功---")
                    break


def stop_server(portlist: list):
    sysstr = platform.system()
    if sysstr == 'Windows':
        os.popen("taskkill /f /im node.exe")
    else:
        for port in portlist:
            cmd = "lsof -i :{0}".format(port)
            plist = os.popen(cmd).readlines()
            plisttmp = plist[1].split("    ")
            plists = plisttmp[1].split(" ")
            os.popen("kill -9 {0}".format(plists[0]))
